package com.colin.juc.java8;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhaodong on 2021/5/23 14:5454
 * email: colinzhaodong@gmail.com
 * desc:
 *
 * @author zhaodong
 */
public class CompletionServiceTest {
    private Integer getPriceByS1(){
        return 28;
    }

    private Integer getPriceByS2(){
        return 22;
    }

    private Integer getPriceByS3(){
        return 35;
    }

    private Integer getMinValue() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
        completionService.submit(this::getPriceByS1);
        completionService.submit(this::getPriceByS2);
        completionService.submit(this::getPriceByS3);
        AtomicInteger minValue = new AtomicInteger(Integer.MAX_VALUE);
        CountDownLatch latch = new CountDownLatch(3);

        for (int i = 0; i < 3; i++) {
               executorService.execute(() ->{
                   Integer r = null;
                   try {
                       r = completionService.take().get();
                   } catch (Exception ignored) {}finally {
                       latch.countDown();
                   }
                   minValue.set(Integer.min(minValue.get(), r));
               });

        }
        latch.await();
        if (latch.getCount() == 0){
            executorService.shutdown();
            if (executorService.isShutdown()){
                System.out.println("线程池已终止");
            }
        }
        return minValue.get();
    }

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CompletionServiceTest completionServiceTest = new CompletionServiceTest();
        System.out.println(completionServiceTest.getMinValue());
    }
}
